<?php

namespace App\Services;

use App\Models\UserCoupon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;

class CouponService
{

    /**
     * 发券
     * @param $user_id 用户ID
     * @param $title 券名称
     * @param $dealer_id 经销商ID
     * @param $type 券类型
     * @param $type_id 关联ID
     * @param $due_at 过期时间
     * @param $valid_at 生效时间
     * @return void
     */
    public function increase($user_id, $title, $dealer_id, $type, $type_id = null, $due_at = null, $valid_at = null)
    {
        $now = date('Y-m-d H:i:s');
        if (!$valid_at) $valid_at = $now;

        $data = [
            'user_id' => $user_id,
            'title' => $title,
            'type' => $type,
            'valid_at' => $valid_at,
            'dealer_id' => $dealer_id
        ];

        $type_id && $data['type_id'] = $type_id;
        $due_at && $data['due_at'] = $due_at;

        $types = implode(',', array_keys(UserCoupon::$typeMap));
        $rules = [
            'user_id' => 'required|integer',
            'title' => 'required|string',
            'dealer_id' => 'required|integer',
            'type' => 'required|in:' . $types,
            'type_id' => 'integer',
            'due_at' => 'date_format:"Y-m-d H:i:s"',
            'valid_at' => 'date_format:"Y-m-d H:i:s"',
        ];
        Validator::make($data, $rules)->validate();
        $coupon = new UserCoupon($data);
        $coupon->save();
        return $coupon;
    }

    /**
     * 核销券
     * @return void
     */
    public function verify(UserCoupon $coupon, $dealer_code, $org_id)
    {
        switch ($coupon->status) {
            case UserCoupon::STATUS_USED:
                throw_invalid_request_exception('coupon-used');
                break;
            case UserCoupon::STATUS_OVERDUE:
                throw_invalid_request_exception('coupon-overdue');
                break;
            case UserCoupon::STATUS_INEFFECTIVE:
                throw_invalid_request_exception('coupon-ineffective');
                break;
        }

        if ($coupon->dealer->code != $dealer_code) {
            throw_invalid_request_exception('dealer-invalid');
        }
        $coupon->used_at = Carbon::now();
        $coupon->org_id = $org_id;
        $coupon->save();
        return $coupon;
    }
}
